<%@ page contentType="text/html;charset=UTF-8" %>
<script>
var system = parent.SYSTEM


function getSearchParam(){
	var searchParam = $("#searchForm").serializeJSON();
   	searchParam.shop=(searchParam.shop=="未选择"?"":searchParam.shop);
   	searchParam.top=(searchParam.top=="未选择"?"":searchParam.top);
   	searchParam.total=(searchParam.total=="未选择"?"":searchParam.total);
   	searchParam["agents.id"]=(searchParam.top||searchParam.total || searchParam.shop);
	if((searchParam["agents.id"]==undefined || searchParam["agents.id"]=="") &&agentsId){
		searchParam["agents.id"]=agentsId;
	}
	return searchParam;
}

$(document).ready(function() {
    $("input[name='setTime']").val(system.beginDate);
	$("input[name='timeEnd']").val(system.endDate);
	$('#wxAgentsRecordingTable').bootstrapTable({

		  //请求方法
               method: 'get',
               //类型json
               dataType: "json",
               //显示刷新按钮
               showRefresh: true,
               //显示切换手机试图按钮
               showToggle: true,
               //显示 内容列下拉框
    	       showColumns: true,
    	       //显示到处按钮
    	       showExport: true,
    	       //tableName: "分销商收入记录导出报表",
    	       //worksheetName: "分销商收入记录",
    	       //显示切换分页按钮
    	       showPaginationSwitch: true,
    	       //最低显示2行
    	       minimumCountColumns: 2,
               //是否显示行间隔色
               striped: true,
               //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
               cache: false,
               //是否显示分页（*）
               pagination: true,
                //排序方式
               sortOrder: "asc",
               //初始化加载第一页，默认第一页
               pageNumber:1,
               //每页的记录行数（*）
               pageSize: 10,
               //可供选择的每页的行数（*）
               pageList: [10, 25, 50, 100],
               //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据
               url: "${ctx}/web/wxAgentsRecording/data",
               //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
               //queryParamsType:'',
               ////查询参数,每次调用是会带上这个参数，可自定义
               queryParams : function(params) {
               		var searchParam=getSearchParam();
					searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
					searchParam.pageSize = params.limit === undefined? -1 : params.limit;
					searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
					   if(!searchParam.setTime){
						   searchParam.setTime = system.beginDate
					   }
					   if(!searchParam.endTime){
						   searchParam.endTime = system.endDate
					   }
					return searchParam;
               },
               //分页方式：client客户端分页，server服务端分页（*）
               sidePagination: "server",
               contextMenuTrigger:"right",//pc端 按右键弹出菜单
               contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
               contextMenu: '#context-menu',
               onContextMenuItem: function(row, $el){
                   if($el.data("item") == "edit"){
                   	window.location = "${ctx}/web/wxAgentsRecording/form?id=" + row.id;
                   } else if($el.data("item") == "delete"){
                        jp.confirm('确认要删除该分销商收入记录记录吗？', function(){
                       	jp.loading();
                       	jp.get("${ctx}/web/wxAgentsRecording/delete?id="+row.id, function(data){
                   	  		if(data.success){
                   	  			$('#wxAgentsRecordingTable').bootstrapTable('refresh');
                   	  			jp.success(data.msg);
                   	  		}else{
                   	  			jp.error(data.msg);
                   	  		}
                   	  	})

                   	});

                   }
               },

               onClickRow: function(row, $el){
               },
               columns: [{
		        checkbox: true

		    }
               ,{
   		        field: 'agents.userName',
   		        title: '分销商',
   		        width: "120px",
   		        sortable: true,
   		     formatter:function(value,row,index){
   		    	 var level=row.agents.agentLevel;
		   		  	if(level == 0){
		   		  		return value;
		        	}else if(level == 1){
		        		return '<span style="color: red;">'+value+'</span>';
		        	}else if(level == 2){
		        		return '<span style="color: blue;">'+value+'</span>';
		        	}else if(level == 3){
		        		return '<span style="color: green;">'+value+'</span>';
		        	}else if(level == 4){
                        return '<span style="color: green;">'+value+'</span>';
                    }
   		     }
   		    }
               ,{
            	   field: 'agents.remarks',
            	   title: '分销商备注',
            	   sortable: true,
            	   formatter:function(value,row,index){
            		   var level=row.agents.agentLevel;
   		   		  	if(level == 0){
   		   		  		return value;
   		        	}else if(level == 1){
   		        		return '<span style="color: red;">'+value+'</span>';
   		        	}else if(level == 2){
   		        		return '<span style="color: blue;">'+value+'</span>';
   		        	}else if(level == 3){
   		        		return '<span style="color: green;">'+value+'</span>';
   		        	}else if(level == 4){
                        return '<span style="color: green;">'+value+'</span>';
                    }
            	   }
               }
			,{
		        field: 'agents.id',
		        title: '所属ID',
		        sortable: true


		    }
			,{
		        field: 'agents.agentLevel',
		        title: '分销商层级',
		        sortable: true,
		        formatter:function(value,row,index){
		        	if(value == 0){
		        		return "公司";
		        	}else if(value == 1){
		        		return '<span style="color: red;">一级代理商</span>';
		        	}else if(value == 2){
		        		return '<span style="color: blue;">二级代理商</span>';
		        	}else if(value == 3){
		        		return '<span style="color: green;">门店</span>';
		        	}else if(value == 4){
                        return '<span style="color: green;">业务员</span>';
                    }

		        }

		    }
			,{
		        field: 'money',
		        title: '收入金额',
		        sortable: true

		    }
			,{
		        field: 'number',
		        title: '订单号',
		        sortable: true

		    }
			,{
		        field: 'orderMoney',
		        title: '订单金额',
		        sortable: true

		    }
			,{
		        field: 'orderTime',
		        title: '开机时长(小时)',
		        sortable: true,
		        formatter:function(value, row , index){
		        	 if(parseFloat(value)>0){
		        		 return parseInt(parseFloat(value) / 60);
		        	 }else{
		        		 return value;
		        	 }
			        }

		    }
			,{
		        field: 'equipment',
		        title: '设备',
		        sortable: true

		    }
			,{
		         field: 'coupon',
		         title: '备注(是否使用优惠券)',
		         sortable: true,
		         formatter:function(value, row , index){
		        	 if(parseFloat(value)>0){
		        		 return "使用优惠券金额为："+value;
		        	 }else{
		        		 return "未使用优惠券";
		        	 }
//			        	return jp.getDictLabel(${fns:toJson(fns:getDictList('yes_no'))}, value, "-");
			        }
		     }
			,{
                       field: 'createDate',
                       title: '时间',
                       sortable: true

                   }
		     ]

		});


	  if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端


		  $('#wxAgentsRecordingTable').bootstrapTable("toggleView");
		}

	  $('#wxAgentsRecordingTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
                'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#wxAgentsRecordingTable').bootstrapTable('getSelections').length);
            $('#edit').prop('disabled', $('#wxAgentsRecordingTable').bootstrapTable('getSelections').length!=1);
        });

		$("#btnImport").click(function(){
			jp.open({
			    type: 1,
			    area: [500, 300],
			    title:"导入数据",
			    content:$("#importBox").html() ,
			    btn: ['下载模板','确定', '关闭'],
				    btn1: function(index, layero){
					  window.location='${ctx}/web/wxAgentsRecording/import/template';
				  },
			    btn2: function(index, layero){
				        var inputForm =top.$("#importForm");
				        var top_iframe = top.getActiveTab().attr("name");//获取当前active的tab的iframe
				        inputForm.attr("target",top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示
				        inputForm.onsubmit = function(){
				        	jp.loading('  正在导入，请稍等...');
				        }
				        inputForm.submit();
					    jp.close(index);
				  },

				  btn3: function(index){
					  jp.close(index);
	    	       }
			});
		});

	  $("#search").click("click", function() {// 绑定查询按扭
		  var time=$('input[name="setTime"]').val();
		  var endTime=$('input[name="endTime"]').val();
		  if(time==''){
			  jp.error("请选择开始时间");

			  return;
		  }
		  if(endTime==''){
			  jp.error("请选择结束时间");

			  return;
		  }
		  $('#wxAgentsRecordingTable').bootstrapTable('refresh');
		});

	 $("#reset").click("click", function() {// 绑定查询按扭
	 	$("#searchForm  input").val("");
	 	$("#searchForm  select").val("");
	 	$("#searchForm  .select-item").html("");
	 	$("input[name='setTime']").val(system.beginDate);
	 	$("input[name='timeEnd']").val(system.endDate);
	 	$('#wxAgentsRecordingTable').bootstrapTable('refresh');
	 });

	 getMoney();
	 isInit=false;
	});

  function getIdSelections() {
        return $.map($("#wxAgentsRecordingTable").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }

  function deleteAll(){

		jp.confirm('确认要删除该分销商收入记录记录吗？', function(){
			jp.loading();
			jp.get("${ctx}/web/wxAgentsRecording/deleteAll?ids=" + getIdSelections(), function(data){
         	  		if(data.success){
         	  			$('#wxAgentsRecordingTable').bootstrapTable('refresh');
         	  			jp.success(data.msg);
         	  		}else{
         	  			jp.error(data.msg);
         	  		}
         	  	})

		})
  }
  function edit(){
	  window.location = "${ctx}/web/wxAgentsRecording/form?id=" + getIdSelections();
  }



function getMoney(){
	var tempSearchParam=getSearchParam();
    if(tempSearchParam.setTime==''){
    	if(isInit==true){
    		tempSearchParam.setTime=system.beginDate;
    	}else{
    		jp.error("请选则开始时间");
    		return;
    	}
    }
    if(tempSearchParam.timeEnd==''){
    	if(isInit==true){
    		  tempSearchParam.timeEnd=system.endDate;
    	}else{
    		jp.error("请选则结束时间");
    		return;
    	}
    }
    if(tempSearchParam.number==''){
    	tempSearchParam.number="0"
    }
    if(tempSearchParam.equipment==''){
    	tempSearchParam.equipment="0"
    }
    var date=new Date(tempSearchParam.setTime);
    var endDate=new Date(tempSearchParam.timeEnd);
    jp.get("${ctx}/web/wxAgentsRecording/getMoney?ids=" + getIdSelections()+"&endTime="+
    		endDate.getTime()+"&time="+date.getTime()+"&equipment="+tempSearchParam.equipment+"&number="+tempSearchParam.number
    		+"&agents.id="+tempSearchParam["agents.id"]+"&shop="+tempSearchParam.shop, function(data){

          jp.success(data.msg);
          console.log(data.msg);
          var htm='订单总金额：'+data.body.s2+' <br/>';
          htm +='分销总收益：'+data.body.s1+' <br/>';
          $('.getMoneys').html(htm);
          console.log(data.body);
      })
}


</script>
